package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSONObject;
import com.yourenbang.lingyun.constants.BizCodeMessages;
import com.yourenbang.lingyun.constants.Constant;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.MerchantStatusEnum;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.table.MerchantEnum;
import com.yourenbang.lingyun.core.exception.BizRuntimeException;
import com.yourenbang.lingyun.core.exception.UserBizException;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.redis.CacheKey;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.*;
import com.yourenbang.lingyun.mapper.Merchant20Mapper;
import com.yourenbang.lingyun.mapper.MerchantEnterprise20Mapper;
import com.yourenbang.lingyun.mapper.MerchantUpdate20Mapper;
import com.yourenbang.lingyun.mapper.UserBaseExtMapper;
import com.yourenbang.lingyun.transaction.mapper.MeMerchantUpdateMapper;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.MerchantEnterpriseSyncDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.MerchantUpdateDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.MigrateDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.PayMerUpdatePO;
import com.yourenbang.lingyun.transaction.web.domain.po.klks.PayMerchantPO;
import com.yourenbang.lingyun.transaction.web.domain.po.klks.PledgeCash;
import com.yourenbang.lingyun.transaction.web.service.migrate.MerchantMigrateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service("merchantMigrateService")
public class MerchantMigrateServiceImpl extends AbstractMigrateService implements MerchantMigrateService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private UserBaseExtMapper userBaseExtMapper;
    @Autowired
    private MeMerchantUpdateMapper merchantUpdateMapper;
    @Autowired
    private MerchantUpdate20Mapper merchantUpdate20Mapper;
    @Autowired
    private Merchant20Mapper merchant20Mapper;
    @Autowired
    private MerchantEnterprise20Mapper merchantEnterprise20Mapper;

    @Override
    public void payMerchant(String optAction, MigrateDTO dto) {
        switch (optAction) {
            case MigrateDTO.OPT_INSERT:
                payMerchantInsert(dto);
                break;
            case MigrateDTO.OPT_UPDATE:
                payMerchantUpdate(dto);
                break;
            case MigrateDTO.OPT_DELETE:
                payMerchantDelete(dto);
                break;
            default:
                KLog.error("[商户-考拉快收-数据同步]通道商户,不支持的数据操作,入参:{}", dto.toJSON());
                throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的数据操作");
        }
    }

    /**
     * 通道商户插入
     * 必须参数：UserId，ProductType
     */
    private void payMerchantInsert(MigrateDTO dto) {

        PayMerchantPO payMerchant = JSONObject.parseObject(dto.getData(), PayMerchantPO.class);
        if (payMerchant == null) {
            KLog.error("[商户-考拉快收-数据同步]通道商户插入,数据解析空,入参:{}", dto.toJSON());
            throw new UserBizException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(payMerchant.getUserId(), payMerchant.getProductType())) {
            KLog.error("[商户-考拉快收-数据同步]通道商户插入,缺失必须参数,入参:{}", dto.toJSON());
            throw new UserBizException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, payMerchant.getUserId(), redis);
        if (StringUtils.isBlank(userBaseId)) {
            KLog.error("[商户-考拉快收-数据同步]通道商户插入,未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new UserBizException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        Merchant20Example oldMerchant20Example = new Merchant20Example();
        oldMerchant20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(payMerchant.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<Merchant20> oldMerchant20List = merchant20Mapper.selectByExample(oldMerchant20Example);
        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            if (StringUtils.equalsAny(payMerchant.getProductType(), "05", "08")) {
                Merchant20Example eposMerchant20Example = new Merchant20Example();
                if (StringUtils.equals(payMerchant.getProductType(), "05")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("08").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                } else if (StringUtils.equals(payMerchant.getProductType(), "08")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("05").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }
                oldMerchant20List = merchant20Mapper.selectByExample(eposMerchant20Example);
            }
        }

        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            Merchant20 merchant20 = fmtMerchantData(payMerchant, userBaseId);
            int inCount = merchant20Mapper.insertSelective(merchant20);
            BizAssertUtils.assertOne(inCount, "添加通道商户失败");
            return;
        }

        Merchant20 oldMerchant20 = oldMerchant20List.get(0);
        fmtMerchantDataV2(oldMerchant20, payMerchant, userBaseId);

        int upCount = merchant20Mapper.updateByPrimaryKey(oldMerchant20);
        BizAssertUtils.assertOne(upCount, "更新通道商户失败");

    }

    /**
     * 通道商户更新
     * 必须参数：UserId，ProductType
     */
    private void payMerchantUpdate(MigrateDTO dto) {
        PayMerchantPO payMerchant = JSONObject.parseObject(dto.getData(), PayMerchantPO.class);
        if (payMerchant == null) {
            KLog.error("[商户-考拉快收-数据同步]通道商户更新,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(payMerchant.getUserId(), payMerchant.getProductType())) {
            KLog.error("[商户-考拉快收-数据同步]通道商户更新,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, payMerchant.getUserId(), redis);
        if (StringUtils.isBlank(userBaseId)) {
            KLog.error("[商户-考拉快收-数据同步]通道商户更新,未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        Merchant20Example oldMerchant20Example = new Merchant20Example();
        oldMerchant20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(payMerchant.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<Merchant20> oldMerchant20List = merchant20Mapper.selectByExample(oldMerchant20Example);
        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            if (StringUtils.equalsAny(payMerchant.getProductType(), "05", "08")) {
                Merchant20Example eposMerchant20Example = new Merchant20Example();
                if (StringUtils.equals(payMerchant.getProductType(), "05")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("08").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                } else if (StringUtils.equals(payMerchant.getProductType(), "08")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("05").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }
                oldMerchant20List = merchant20Mapper.selectByExample(eposMerchant20Example);
            }
        }

        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            KLog.error("[商户-考拉快收-数据同步]通道商户更新,未找到原通道商户数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未找到原通道商户数据");
        }

        Merchant20 oldMerchant20 = oldMerchant20List.get(0);
        fmtMerchantDataV2(oldMerchant20, payMerchant, userBaseId);

        int upCount = merchant20Mapper.updateByPrimaryKey(oldMerchant20);
        BizAssertUtils.assertOne(upCount, "更新通道商户失败");
    }

//    /**
//     * 通道商户更新空值
//     * 必须参数：UserId，ProductType
//     */
//    private void payMerchantUpdateNull(MigrateDTO dto) {
//        PayMerchantPO payMerchant = JSONObject.parseObject(dto.getData(), PayMerchantPO.class);
//        if (payMerchant == null) {
//            KLog.error("[商户-考拉快收-数据同步]通道商户更新空值,数据解析空,入参:{}", dto.toJSON());
//            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
//        }
//
//        if (StringUtils.isAnyBlank(payMerchant.getUserId(), payMerchant.getProductType())) {
//            KLog.error("[商户-考拉快收-数据同步]通道商户更新空值,缺失必须参数,入参:{}", dto.toJSON());
//            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
//        }
//
//        String userBaseId = getUserBaseId(userBaseExtMapper, payMerchant.getUserId(), redis);
//        if (StringUtils.isBlank(userBaseId)) {
//            KLog.error("[商户-考拉快收-数据同步]通道商户更新空值,未获取到凌云用户id,入参:{}", dto.toJSON());
//            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
//        }
//
//        Merchant20Example oldMerchant20Example = new Merchant20Example();
//        oldMerchant20Example.createCriteria()
//                .andUserBaseIdEqualTo(userBaseId)
//                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(payMerchant.getProductType()).getCode())
//                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
//        List<Merchant20> oldMerchant20List = merchant20Mapper.selectByExample(oldMerchant20Example);
//        if (CollectionUtils.isEmpty(oldMerchant20List)) {
//            KLog.error("[商户-考拉快收-数据同步]通道商户更新空值,未找到原通道商户数据,入参:{}", dto.toJSON());
//            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未找到原通道商户数据");
//        }
//
//        Merchant20 oldMerchant20 = oldMerchant20List.get(0);
//        if (payMerchant.getAssessBeginTime() != null) {
//            int upCount = merchantMapper.setTerminalActiveTimeNull(oldMerchant20.getMerchantId(), PlatNoEnums.KLKS.getCode());
//            BizAssertUtils.assertOne(upCount, "更新通道商户失败");
//        }
//    }

    /**
     * 通道商户删除
     */
    private void payMerchantDelete(MigrateDTO dto) {
        KLog.error("[商户-考拉快收-数据同步]通道商户删除,不支持的数据操作,入参:{}", dto.toJSON());
        throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的数据操作");
    }

    /**
     * 格式化通道商户数据
     */
    @Override
    public Merchant20 fmtMerchantData(PayMerchantPO payMerchant, String userBaseId) {
        Merchant20 merchant20 = new Merchant20();
        merchant20.setMerchantNo(payMerchant.getMerNo());
        merchant20.setMerchantName(payMerchant.getMerName());
        merchant20.setUserBaseId(userBaseId);
        merchant20.setRealName(payMerchant.getRealName());
        merchant20.setIdCard(payMerchant.getIdCard());
        merchant20.setOpenBank(payMerchant.getOpenBank());
        merchant20.setOpenBankNo(payMerchant.getOpenBankNo());
        merchant20.setOpenBankAddress(payMerchant.getOpenBankAddress());
        merchant20.setBankCard(payMerchant.getBankCard());
        merchant20.setPhone(payMerchant.getPhone());
        merchant20.setEmail(payMerchant.getEmail());
        merchant20.setProtocolUrl(payMerchant.getProtocolUrl());
        merchant20.setRateBorrow(payMerchant.getRateBorrow());
        merchant20.setRateFixedFlag(payMerchant.getRateFixedFlag());
        merchant20.setRateCredit(payMerchant.getRateCredit());
        if (StringUtils.isNotBlank(payMerchant.getD0Flag())) {
            merchant20.setD0Flag(new Byte(payMerchant.getD0Flag()));
        }
        merchant20.setContractOrderNo(payMerchant.getContractOrderNo());
        merchant20.setContractId(payMerchant.getContractId());
        merchant20.setContractIds(payMerchant.getContractIds());
        merchant20.setFictitiousMobile(payMerchant.getFictitiousMobile());
        merchant20.setTerminalId(payMerchant.getTermId());
        merchant20.setActivationCodes(payMerchant.getActivationCodes());
        merchant20.setMerchantActiveTime(payMerchant.getActiveTime());
        merchant20.setTerminalActiveTime(payMerchant.getAssessBeginTime());
        merchant20.setProvinceCode(payMerchant.getProvinceCode());
        merchant20.setCityCode(payMerchant.getCityCode());
        merchant20.setDistrictCode(payMerchant.getDistrictCode());
        merchant20.setLocation(payMerchant.getLocation());
        merchant20.setUploadFlag(payMerchant.getUploadFlag());
        merchant20.setUpdateCardFlag(fmtBooleanStr(payMerchant.getUpdateCardFlag()));
        merchant20.setMerchantAuthFlag(fmtBooleanStr(payMerchant.getMerAuthFlag()));
        merchant20.setChannelId(ChannelIdEnums.convertKuaiShouProductType(payMerchant.getProductType()).getCode());
        merchant20.setPlatNo(PlatNoEnums.KLKS.getCode());
        merchant20.setStatus(fmtMerchantStatus(payMerchant.getStatus()));
        if (StringUtils.isNotBlank(payMerchant.getBountyFlag())) {
            merchant20.setBountyFlag(new Byte(fmtBooleanStr(payMerchant.getBountyFlag())));
        }
        merchant20.setDiscountsRateBeginTime(payMerchant.getDiscountsRateBeginTime());
        merchant20.setDiscountsRateEndTime(payMerchant.getDiscountsRateEndTime());
        merchant20.setDiscountsRatePastFlag(fmtBooleanStr(payMerchant.getDiscountsRatePastFlag()));
        merchant20.setRemarks(payMerchant.getRemarks());
        merchant20.setIsDel(Constant.NORMAL);
        merchant20.setCreateTime(payMerchant.getCreateTime());
        merchant20.setUpdateTime(payMerchant.getUpdateTime() == null ? LocalDateTime.now() : payMerchant.getUpdateTime());
        cacheMerOping(merchant20, payMerchant.getOpenMerIngExpir());
        return merchant20;
    }

    private void fmtMerchantDataV2(Merchant20 merchant20, PayMerchantPO payMerchant, String userBaseId) {
        merchant20.setMerchantNo(payMerchant.getMerNo());
        merchant20.setMerchantName(payMerchant.getMerName());
        merchant20.setUserBaseId(userBaseId);
        merchant20.setRealName(payMerchant.getRealName());
        merchant20.setIdCard(payMerchant.getIdCard());
        merchant20.setOpenBank(payMerchant.getOpenBank());
        merchant20.setOpenBankNo(payMerchant.getOpenBankNo());
        merchant20.setOpenBankAddress(payMerchant.getOpenBankAddress());
        merchant20.setBankCard(payMerchant.getBankCard());
        merchant20.setPhone(payMerchant.getPhone());
        merchant20.setEmail(payMerchant.getEmail());
        merchant20.setProtocolUrl(payMerchant.getProtocolUrl());
        merchant20.setRateBorrow(payMerchant.getRateBorrow());
        merchant20.setRateFixedFlag(payMerchant.getRateFixedFlag());
        merchant20.setRateCredit(payMerchant.getRateCredit());
        if (StringUtils.isNotBlank(payMerchant.getD0Flag())) {
            merchant20.setD0Flag(new Byte(payMerchant.getD0Flag()));
        }
        merchant20.setContractOrderNo(payMerchant.getContractOrderNo());
        merchant20.setContractId(payMerchant.getContractId());
        merchant20.setContractIds(payMerchant.getContractIds());
        merchant20.setFictitiousMobile(payMerchant.getFictitiousMobile());
        merchant20.setTerminalId(payMerchant.getTermId());
        merchant20.setActivationCodes(payMerchant.getActivationCodes());
        merchant20.setMerchantActiveTime(payMerchant.getActiveTime());
        merchant20.setTerminalActiveTime(payMerchant.getAssessBeginTime());
        merchant20.setProvinceCode(payMerchant.getProvinceCode());
        merchant20.setCityCode(payMerchant.getCityCode());
        merchant20.setDistrictCode(payMerchant.getDistrictCode());
        merchant20.setLocation(payMerchant.getLocation());
        merchant20.setUploadFlag(payMerchant.getUploadFlag());
        merchant20.setUpdateCardFlag(fmtBooleanStr(payMerchant.getUpdateCardFlag()));
        merchant20.setMerchantAuthFlag(fmtBooleanStr(payMerchant.getMerAuthFlag()));
        merchant20.setChannelId(ChannelIdEnums.convertKuaiShouProductType(payMerchant.getProductType()).getCode());
        merchant20.setPlatNo(PlatNoEnums.KLKS.getCode());
        merchant20.setStatus(fmtMerchantStatus(payMerchant.getStatus()));
        if (StringUtils.isNotBlank(payMerchant.getBountyFlag())) {
            merchant20.setBountyFlag(new Byte(fmtBooleanStr(payMerchant.getBountyFlag())));
        }
        merchant20.setDiscountsRateBeginTime(payMerchant.getDiscountsRateBeginTime());
        merchant20.setDiscountsRateEndTime(payMerchant.getDiscountsRateEndTime());
        merchant20.setDiscountsRatePastFlag(fmtBooleanStr(payMerchant.getDiscountsRatePastFlag()));
        merchant20.setRemarks(payMerchant.getRemarks());
        merchant20.setIsDel(Constant.NORMAL);
        merchant20.setCreateTime(payMerchant.getCreateTime());
        merchant20.setUpdateTime(payMerchant.getUpdateTime() == null ? LocalDateTime.now() : payMerchant.getUpdateTime());
        merchant20.setCloseStatus(payMerchant.getCloseStatus());
        merchant20.setSupplementStatus(payMerchant.getSupplementStatus());
        merchant20.setSupplementFailReason(payMerchant.getSupplementFailReason());
        merchant20.setMccCode(payMerchant.getMccCode());
        cacheMerOping(merchant20, payMerchant.getOpenMerIngExpir());
    }

    /**
     * 商户开通中
     */
    private void cacheMerOping(Merchant20 merchant20, Integer expir) {
        if (expir == null) {
            return;
        }
        CacheKey key = new CacheKey(CacheKey.CacheKeyPrefix2.pay,
                StringUtils.join(new String[]{"cacheMerOping", merchant20.getChannelId().toString(), merchant20.getUserBaseId()}, ":"));
        log.debug("[格式化通道商户数据]缓存商户开通中,key:{}", key.getKeyStr());
        redis.set(key, merchant20.getUserBaseId(), expir);
    }

    /**
     * 格式化通道商户状态
     */
    private Short fmtMerchantStatus(String klksStatus) {
        if (StringUtils.isBlank(klksStatus)) {
            return null;
        }
        if (StringUtils.equals(klksStatus, PayMerchantPO.STATUS_INIT)) {
            return MerchantStatusEnum.STATUS_100.getCode();
        } else if (StringUtils.equals(klksStatus, PayMerchantPO.STATUS_OPEN)) {
            return MerchantStatusEnum.STATUS_300.getCode();
        } else if (StringUtils.equals(klksStatus, PayMerchantPO.STATUS_FAIL)) {
            return MerchantStatusEnum.STATUS_210.getCode();
        } else {
            KLog.error("[商户-考拉快收-数据同步]格式化通道商户状态,不支持的通道商户状态,入参:{}", klksStatus);
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的通道商户状态");
        }
    }

    /**
     * 押金
     */
    @Override
    public void pledgeCash(String optAction, MigrateDTO dto) {
        switch (optAction) {
            case MigrateDTO.OPT_INSERT:
                pledgeCashInsert(dto);
                break;
            case MigrateDTO.OPT_UPDATE:
                pledgeCashUpdate(dto);
                break;
            case MigrateDTO.OPT_DELETE:
                pledgeCashDelete(dto);
                break;
            default:
                KLog.error("[商户-考拉快收-数据同步]押金,不支持的数据操作,入参:{}", dto.toJSON());
                throw new UserBizException(BizCodeMessages.UNKNOWN_ERROR, "不支持的数据操作");
        }
    }

    /**
     * 押金插入
     * 必须参数：UserId，ProductType
     */
    private void pledgeCashInsert(MigrateDTO dto) {

        PledgeCash pledgeCash = JSONObject.parseObject(dto.getData(), PledgeCash.class);
        if (pledgeCash == null) {
            KLog.error("[商户-考拉快收-数据同步]押金插入,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(pledgeCash.getUserId(), pledgeCash.getProductType())) {
            KLog.error("[商户-考拉快收-数据同步]押金插入,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, pledgeCash.getUserId(), redis);
        if (StringUtils.isBlank(userBaseId)) {
            KLog.error("[商户-考拉快收-数据同步]押金插入,未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        Merchant20Example oldMerchant20Example = new Merchant20Example();
        oldMerchant20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(pledgeCash.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<Merchant20> oldMerchant20List = merchant20Mapper.selectByExample(oldMerchant20Example);
        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            if (StringUtils.equalsAny(pledgeCash.getProductType(), "05", "08")) {
                Merchant20Example eposMerchant20Example = new Merchant20Example();
                if (StringUtils.equals(pledgeCash.getProductType(), "05")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("08").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                } else if (StringUtils.equals(pledgeCash.getProductType(), "08")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("05").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }
                oldMerchant20List = merchant20Mapper.selectByExample(eposMerchant20Example);
            }
        }

        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            KLog.info("[商户-考拉快收-数据同步]押金插入,未找到原通道商户数据,插入押金数据,入参:{}", dto.toJSON());
            Merchant20 merchant20 = fmtPledgeCashData(pledgeCash);
            merchant20.setUserBaseId(userBaseId);
            merchant20.setChannelId(ChannelIdEnums.convertKuaiShouProductType(pledgeCash.getProductType()).getCode());
            merchant20.setPlatNo(PlatNoEnums.KLKS.getCode());
            merchant20.setIsDel(Constant.NORMAL);
            int inCount = merchant20Mapper.insertSelective(merchant20);
            BizAssertUtils.assertOne(inCount, "添加押金数据失败");
            return;
        }

        Merchant20 oldMerchant20 = oldMerchant20List.get(0);
        Merchant20 merchant20 = fmtPledgeCashData(pledgeCash);
        merchant20.setPledgeCashPayType(StringUtils.isNotBlank(merchant20.getPledgeCashPayGetway()) ? new Short("100") : new Short("200"));
        merchant20.setMerchantId(oldMerchant20.getMerchantId());
        int upCount = merchant20Mapper.updateByPrimaryKeySelective(merchant20);
        BizAssertUtils.assertOne(upCount, "更新通道商户失败");
    }

    /**
     * 押金更新
     * 必须参数：UserId，ProductType
     */
    private void pledgeCashUpdate(MigrateDTO dto) {
        PledgeCash pledgeCash = JSONObject.parseObject(dto.getData(), PledgeCash.class);
        if (pledgeCash == null) {
            KLog.error("[商户-考拉快收-数据同步]押金更新,数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(pledgeCash.getUserId(), pledgeCash.getProductType())) {
            KLog.error("[商户-考拉快收-数据同步]押金更新,缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, pledgeCash.getUserId(), redis);
        if (StringUtils.isBlank(userBaseId)) {
            KLog.error("[商户-考拉快收-数据同步]押金更新,未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        Merchant20Example oldMerchant20Example = new Merchant20Example();
        oldMerchant20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(pledgeCash.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<Merchant20> oldMerchant20List = merchant20Mapper.selectByExample(oldMerchant20Example);
        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            if (StringUtils.equalsAny(pledgeCash.getProductType(), "05", "08")) {
                Merchant20Example eposMerchant20Example = new Merchant20Example();
                if (StringUtils.equals(pledgeCash.getProductType(), "05")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("08").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                } else if (StringUtils.equals(pledgeCash.getProductType(), "08")) {
                    eposMerchant20Example.createCriteria()
                            .andUserBaseIdEqualTo(userBaseId)
                            .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType("05").getCode())
                            .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
                }
                oldMerchant20List = merchant20Mapper.selectByExample(eposMerchant20Example);
            }
        }

        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            KLog.error("[商户-考拉快收-数据同步]押金更新,未找到原通道商户数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未找到原通道商户数据");
        }

        Merchant20 oldMerchant20 = oldMerchant20List.get(0);
        Merchant20 merchant20 = fmtPledgeCashData(pledgeCash);
        merchant20.setMerchantId(oldMerchant20.getMerchantId());
        int upCount = merchant20Mapper.updateByPrimaryKeySelective(merchant20);
        BizAssertUtils.assertOne(upCount, "更新通道商户失败");
    }


    /**
     * 格式化通道商户数据
     */
    @Override
    public Merchant20 fmtPledgeCashData(PledgeCash pledgeCash) {
        Merchant20 merchant20 = new Merchant20();
        merchant20.setPledgeCash(pledgeCash.getAmount());
        merchant20.setPledgeCashReturn(pledgeCash.getRelieveAmount());
        merchant20.setPledgeCashOrderNo(pledgeCash.getOrderNo());
        merchant20.setPledgeCashSerialNo(pledgeCash.getSerialNo());
//        merchant20.setPledgeCashPayGetway(getPayType(pledgeCash.getPayType()));
        merchant20.setPledgeCashStatus(fmtPledgeCashStatus(pledgeCash.getStatus()));
        merchant20.setPledgeCashSuccessTime(pledgeCash.getActiveTime());
        merchant20.setMerchantPledgeCashPolicyId(4);
        return merchant20;
    }

    /**
     * 格式化通道商户押金状态
     */
    private Short fmtPledgeCashStatus(Integer klksStatus) {
        if (klksStatus == null) {
            return null;
        }
        if (PledgeCash.STATUS_NO_0.equals(klksStatus)) {
            return MerchantEnum.PledgeCashStatusEnum.STATUS_100.getCode();
        } else if (PledgeCash.STATUS_SUCC_1.equals(klksStatus)) {
            return MerchantEnum.PledgeCashStatusEnum.STATUS_200.getCode();
        } else if (PledgeCash.STATUS_RETURNED_2.equals(klksStatus)) {
            return MerchantEnum.PledgeCashStatusEnum.STATUS_600.getCode();
        } else if (PledgeCash.STATUS_REACH_3.equals(klksStatus)) {
            return MerchantEnum.PledgeCashStatusEnum.STATUS_400.getCode();
        } else if (PledgeCash.STATUS_FAILURE_4.equals(klksStatus)) {
            return MerchantEnum.PledgeCashStatusEnum.STATUS_420.getCode();
        } else if (PledgeCash.STATUS_REFUND_ING_10.equals(klksStatus)) {
            return MerchantEnum.PledgeCashStatusEnum.STATUS_700.getCode();
        } else if (PledgeCash.STATUS_REFUNDED_11.equals(klksStatus)) {
            return MerchantEnum.PledgeCashStatusEnum.STATUS_710.getCode();
        } else {
            KLog.error("[商户-考拉快收-数据同步]格式化通道商户押金状态,不支持的通道商户押金状态,入参:{}", klksStatus);
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的通道商户押金状态");
        }
    }

    /**
     * 押金删除
     */
    private void pledgeCashDelete(MigrateDTO dto) {
        KLog.error("[商户-考拉快收-数据同步]押金删除,不支持的数据操作,入参:{}", dto.toJSON());
        throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "不支持的数据操作");
    }

    /**
     * 商户企业信息同步
     */
    @Override
    public void merchantEnterprise(MigrateDTO dto) {

        MerchantEnterpriseSyncDTO enterpriseSyncDTO = JSONObject.parseObject(dto.getData(), MerchantEnterpriseSyncDTO.class);
        if (enterpriseSyncDTO == null) {
            KLog.error("[商户企业信息同步]数据解析空,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "数据解析空");
        }

        if (StringUtils.isAnyBlank(enterpriseSyncDTO.getUserId(), enterpriseSyncDTO.getProductType())) {
            KLog.error("[商户企业信息同步]缺失必须参数,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "缺失必须参数");
        }

        String userBaseId = getUserBaseId(userBaseExtMapper, enterpriseSyncDTO.getUserId(), redis);
        if (StringUtils.isBlank(userBaseId)) {
            KLog.error("[商户企业信息同步]未获取到凌云用户id,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未获取到凌云用户id");
        }

        MerchantEnterprise20Example oldMerchantEnterprise20Example = new MerchantEnterprise20Example();
        oldMerchantEnterprise20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(enterpriseSyncDTO.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<MerchantEnterprise20> oldMerchant20List = merchantEnterprise20Mapper.selectByExample(oldMerchantEnterprise20Example);
        MerchantEnterprise20 enterprise20 = fmtMerchantEnterprise20(enterpriseSyncDTO, userBaseId);
        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            int inEn = merchantEnterprise20Mapper.insertSelective(enterprise20);
            BizAssertUtils.assertOne(inEn, "插入商户企业信息失败");
        } else {
            enterprise20.setMerchantEnterpriseId(oldMerchant20List.get(0).getMerchantEnterpriseId());
            int upEn = merchantEnterprise20Mapper.updateByPrimaryKeySelective(enterprise20);
            BizAssertUtils.assertOne(upEn, "更新商户企业信息失败");
        }
    }

    @Override
    public void merchantUpdate(MigrateDTO dto) {
        KLog.info("处理商户变更同步mq:{}",dto.toJSON());
        if (StringUtils.equals(dto.getOpt(),MigrateDTO.OPT_INSERT)){
            PayMerUpdatePO payMerUpdatePO = JSONObject.parseObject(dto.getData(), PayMerUpdatePO.class);
            MerchantUpdate20 merchantUpdate20 = new MerchantUpdate20();

            merchantUpdate20.setUserBaseId(getUserBaseId(userBaseExtMapper, payMerUpdatePO.getUserId(), redis));
            merchantUpdate20.setMerchantNo(payMerUpdatePO.getMerNo());
            merchantUpdate20.setContractId(payMerUpdatePO.getContractId());
            merchantUpdate20.setPlatNo(PlatNoEnums.KLKS.getCode());
            merchantUpdate20.setChannelId(ChannelIdEnums.convertKuaiShouProductType(payMerUpdatePO.getProductType()).getCode());
            merchantUpdate20.setType(payMerUpdatePO.getType());
            merchantUpdate20.setUpdateIntValue(payMerUpdatePO.getRate());
            merchantUpdate20.setUpdateStrValue(payMerUpdatePO.getCardNo());
            merchantUpdate20.setStatus(new Short(payMerUpdatePO.getStatus()));
            merchantUpdate20.setRemarks(payMerUpdatePO.getRemarks());
            merchantUpdate20Mapper.insertSelective(merchantUpdate20);
        } else if(StringUtils.equals(dto.getOpt(),MigrateDTO.OPT_MER_UPDATE_STATUS)){
            MerchantUpdateDTO merchantUpdateDTO = JSONObject.parseObject(dto.getData(), MerchantUpdateDTO.class);
            merchantUpdateMapper.updateStatus(merchantUpdateDTO);
        }  else if(StringUtils.equals(dto.getOpt(),MigrateDTO.OPT_MER_UPDATE_HISTORY)){
            MerchantUpdateDTO merchantUpdateDTO = JSONObject.parseObject(dto.getData(), MerchantUpdateDTO.class);
            merchantUpdateDTO.setUserBaseId(getUserBaseId(userBaseExtMapper, merchantUpdateDTO.getUserId(), redis));
            merchantUpdateDTO.setChannelId(ChannelIdEnums.convertKuaiShouProductType(merchantUpdateDTO.getProductType()).getCode());
            merchantUpdateMapper.updateHistoryStatus(merchantUpdateDTO);
        }
        KLog.info("处理商户变更同步mq结束,入参:{}",dto.toJSON());
        return;
    }

    /**
     * 格式化商户企业信息
     */
    private MerchantEnterprise20 fmtMerchantEnterprise20(MerchantEnterpriseSyncDTO dto, String userBaseId) {
        Merchant20Example oldMerchant20Example = new Merchant20Example();
        oldMerchant20Example.createCriteria()
                .andUserBaseIdEqualTo(userBaseId)
                .andChannelIdEqualTo(ChannelIdEnums.convertKuaiShouProductType(dto.getProductType()).getCode())
                .andPlatNoEqualTo(PlatNoEnums.KLKS.getCode());
        List<Merchant20> oldMerchant20List = merchant20Mapper.selectByExample(oldMerchant20Example);

        if (CollectionUtils.isEmpty(oldMerchant20List)) {
            KLog.error("[格式化商户企业信息]通道商户更新,未找到通道商户数据,入参:{}", dto.toJSON());
            throw new BizRuntimeException(BizCodeMessages.UNKNOWN_ERROR, "未找到通道商户数据");
        }

        Merchant20 oldMerchant20 = oldMerchant20List.get(0);
        MerchantEnterprise20 enterprise = new MerchantEnterprise20();
        enterprise.setUserBaseId(userBaseId);
        enterprise.setMerchantId(oldMerchant20.getMerchantId());
        enterprise.setLegalPersonName(dto.getLegalPersonName());
        enterprise.setBusinessLicenseName(dto.getBusinessLicenseName());
        enterprise.setBusinessLicenseCode(dto.getBusinessLicenseCode());
        enterprise.setBusinessLicenseBeginDate(dto.getBusinessLicenseBeginDate());
        enterprise.setBusinessLicenseEndDate(dto.getBusinessLicenseEndDate());
        enterprise.setEnterpriseAddress(dto.getEnterpriseAddress());
        enterprise.setBusinessLicensePhoto(dto.getBusinessLicensePhoto());
        enterprise.setEnterpriseDoorPhoto(dto.getEnterpriseDoorPhoto());
        enterprise.setCashierDeskPhoto(dto.getCashierDeskPhoto());
        enterprise.setShopPhoto(dto.getShopPhoto());
        enterprise.setChannelId(ChannelIdEnums.convertKuaiShouProductType(dto.getProductType()).getCode());
        enterprise.setPlatNo(PlatNoEnums.KLKS.getCode());
        return enterprise;
    }

}
